package com.hj.saapp.common.manager;

import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.location.LocationManager;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.net.wifi.WifiManager;
import android.os.Handler;

import com.hj.saapp.BCDApplication;

import java.net.InetAddress;


/**
 * 类说明：
 * 
 * @author YZ
 * @date 2015年5月25日
 * @version 1.0
 */

public class NetworkManager
{
    
    public static final String NETWORK_CLASS_UNKNOWN = "UNKNOWN";
    
    public static final String NETWORK_CLASS_2_G = "2G";
    
    public static final String NETWORK_CLASS_3_G = "3G";
    
    public static final String NETWORK_CLASS_4_G = "4G";
    
    public static final String NETWORK_CLASS_WIFI = "WIFI";
    
    private static NetworkManager manager;

    public boolean isGetHost() {
        return isGetHost;
    }

    public void setIsGetHost(boolean isGetHost) {
        this.isGetHost = isGetHost;
    }

    public boolean isGetHost = false;
    
    public static NetworkManager getNetworkManager()
    {
        if (manager == null)
        {
            manager = new NetworkManager();
        }

        return manager;
    }

//    public void initNetwork(final Handler handler) {
//
//        Thread thread = new Thread(new Runnable() {
//            @Override
//            public void run() {
//
//                //初始化业务模型
//                final NetWorkConfig nwc = new NetWorkConfig();
//                nwc.retries = 1;
//                nwc.timeout = 20000;//
//                nwc.encode = "GBK";
//                try {
//                    DoMainModelManager.initDoMainModel(BCDApplication.getApp(), nwc);
//                } catch (Exception e) {
//                    e.printStackTrace();
//                }
//                if (true)
//                {
//                    //nwc.port = 8030;
//                    //nwc.url.add("http://101.200.187.77");
////                    http://183.62.248.82:18083/heimao/
////                    nwc.port = 18083;
////                    nwc.url.add("http://183.62.248.82");
//
//                    //阿里云
////                    nwc.port = 28082;
////                    nwc.url.add("http://120.25.60.198");
//                   // 外网
////                    nwc.port = 18083;
////                    nwc.url.add("http://183.62.248.82");
//                    //内网服务器
////                    nwc.port = 8083;
////                    nwc.url.add("http://192.168.8.100");
//
////                    nwc.port = 80;
////                    nwc.url.add("http://192.168.9.50");
//
////                    nwc.port = 80;
////                    nwc.url.add("http://192.168.9.59");
//
////                    nwc.port = 80;
////                    nwc.url.add("http://192.168.8.191");
//
////                    nwc.port = 80;
////                    nwc.url.add("http://192.168.9.42");
//
//                       nwc.port = 80;
//                        nwc.url.add("http://"+NetworkManager.getNetworkManager().getIP("test.heimaoyc.com",handler));
//
////                    nwc.port = 80;
////                    nwc.url.add("http://192.168.8.58");
//
////                    nwc.port = 80;
////                    nwc.url.add("http://192.168.8.191");
//
////                    nwc.port = 8080;
////                    nwc.url.add("http://192.168.8.42");
//
////                    nwc.port = 80;
////                    nwc.url.add("http://192.168.45.2");
////                      nwc.port = 8080;
////                      nwc.url.add("http://192.168.8.88");
//
//
//
//                }
//                else
//                {
//                    nwc.port = 80;
//                    nwc.url.add("http://"+NetworkManager.getNetworkManager().getIP("api.heimaoyc.cn",handler));
//                }
//
//                try {
//                    DoMainModelManager.initDoMainModel(BCDApplication.getApp(), nwc);
//                } catch (Exception e) {
//                    e.printStackTrace();
//                }
//                DoMainModelManager.setDebugger(true);
//                NetworkManager.getNetworkManager().setIsGetHost(true);
//                if (handler != null)
//                {
//                    handler.sendEmptyMessage(1);
//                }
//
//            }
//        });
//        thread.start();
//    }

//    public void initNetwork() {
//
//
//
//                final NetWorkConfig nwc = new NetWorkConfig();
//                nwc.retries = 1;
//                nwc.timeout = 1000*10;//
//                nwc.encode = "GBK";
//                nwc.port = 80;
//                nwc.url.add("http://120.25.60.198");
////                nwc.port = 8030;
////                nwc.url.add("http://101.200.187.77");
//                try {
//                    DoMainModelManager.initDoMainModel(BcDriverApplication.getApp(), nwc);
//                } catch (Exception e) {
//                    e.printStackTrace();
//                }
//                DoMainModelManager.setDebugger(true);
//                NetworkManager.getNetworkManager().setIsGetHost(true);
//    }
    
    // // 手机网络类型
    // public static final int NETTYPE_WIFI = 0x01;
    //
    // public static final int NETTYPE_CMWAP = 0x02;
    //
    // public static final int NETTYPE_CMNET = 0x03;
    
    /**
     * 检测网络是否可用
     * 
     * @return
     */
    public boolean isNetworkConnected()
    {
        ConnectivityManager cm =
            (ConnectivityManager) BCDApplication.getApp().getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo ni = null;
        if (cm != null)
        {
            ni = cm.getActiveNetworkInfo();
        }
        return ni != null && ni.isConnected();
    }
    
    /**
     * 获取当前网络类型
     * 
     */
    public String getNetworkType()
    {
        String netType = NETWORK_CLASS_UNKNOWN;
        ConnectivityManager connectivityManager =
            (ConnectivityManager)BCDApplication.getApp().getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
        if (networkInfo == null)
        {
            return netType;
        }
        int nType = networkInfo.getType();
        if (nType == ConnectivityManager.TYPE_MOBILE)
        {
            
            netType = String.valueOf(networkInfo.getSubtype()); // String.valueOf(networkInfo.getSubtype()) +
                                                                // networkInfo.getExtraInfo();
            // getNetworkClass(networkInfo.getSubtype());
            
            // String extraInfo = networkInfo.getExtraInfo();
            // if (!StringUtils.isEmpty(extraInfo))
            // {
            // if (extraInfo.toLowerCase().equals("cmnet"))
            // {
            // netType = NETTYPE_CMNET;
            // }
            // else
            // {
            // netType = NETTYPE_CMWAP;
            // }
            // }
        }
        else if (nType == ConnectivityManager.TYPE_WIFI)
        {
            netType = NETWORK_CLASS_WIFI;
        }
        // L.d("Stefan", "network type: " + netType);
        return netType;
    }
    
    // private String getNetworkClass(int networkType)
    // {
    // L.d("Stefan", "subType: " + networkType);
    // switch (networkType)
    // {
    // case NETWORK_TYPE_GPRS:
    // case NETWORK_TYPE_EDGE:
    // case NETWORK_TYPE_CDMA:
    // case NETWORK_TYPE_1xRTT:
    // case NETWORK_TYPE_IDEN:
    // return NETWORK_CLASS_2_G;
    // case NETWORK_TYPE_UMTS:
    // case NETWORK_TYPE_EVDO_0:
    // case NETWORK_TYPE_EVDO_A:
    // case NETWORK_TYPE_HSDPA:
    // case NETWORK_TYPE_HSUPA:
    // case NETWORK_TYPE_HSPA:
    // case NETWORK_TYPE_EVDO_B:
    // case NETWORK_TYPE_EHRPD:
    // case NETWORK_TYPE_HSPAP:
    // return NETWORK_CLASS_3_G;
    // case NETWORK_TYPE_LTE:
    // return NETWORK_CLASS_4_G;
    // default:
    // return NETWORK_CLASS_UNKNOWN;
    // }
    // }
    
    /** Network type is unknown */
    public static final int NETWORK_TYPE_UNKNOWN = 0;
    
    /** Current network is GPRS */
    public static final int NETWORK_TYPE_GPRS = 1;
    
    /** Current network is EDGE */
    public static final int NETWORK_TYPE_EDGE = 2;
    
    /** Current network is UMTS */
    public static final int NETWORK_TYPE_UMTS = 3;
    
    /** Current network is CDMA: Either IS95A or IS95B */
    public static final int NETWORK_TYPE_CDMA = 4;
    
    /** Current network is EVDO revision 0 */
    public static final int NETWORK_TYPE_EVDO_0 = 5;
    
    /** Current network is EVDO revision A */
    public static final int NETWORK_TYPE_EVDO_A = 6;
    
    /** Current network is 1xRTT */
    public static final int NETWORK_TYPE_1xRTT = 7;
    
    /** Current network is HSDPA */
    public static final int NETWORK_TYPE_HSDPA = 8;
    
    /** Current network is HSUPA */
    public static final int NETWORK_TYPE_HSUPA = 9;
    
    /** Current network is HSPA */
    public static final int NETWORK_TYPE_HSPA = 10;
    
    /** Current network is iDen */
    public static final int NETWORK_TYPE_IDEN = 11;
    
    /** Current network is EVDO revision B */
    public static final int NETWORK_TYPE_EVDO_B = 12;
    
    /** Current network is LTE */
    public static final int NETWORK_TYPE_LTE = 13;
    
    /** Current network is eHRPD */
    public static final int NETWORK_TYPE_EHRPD = 14;
    
    /** Current network is HSPA+ */
    public static final int NETWORK_TYPE_HSPAP = 15;

    public String  getIP(String name,Handler handler) {
        InetAddress address = null;
        while (true)
        {
            try {
                address = InetAddress.getByName(name);
                if (address != null && address.getHostAddress() != null)
                {
                    break;
                }
            } catch (Exception e) {
                if (handler != null)
                {
                    handler.sendEmptyMessage(2);
                    handler = null;
                }
            }

        }



        return address.getHostAddress().toString();
    }

    /**
     * WIFI网络开关  */
    public void toggleWiFi(boolean enabled) {
        WifiManager wm = (WifiManager) BCDApplication.getApp()
                .getSystemService(Context.WIFI_SERVICE);
        wm.setWifiEnabled(enabled);
    }

    /**
     * 判断GPS是否开启，GPS或者AGPS开启一个就认为是开启的
     * @param context
     * @return true 表示开启
     */
    public static final boolean isOPen(final Context context) {
        LocationManager locationManager
                = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
        // 通过GPS卫星定位，定位级别可以精确到街（通过24颗卫星定位，在室外和空旷的地方定位准确、速度快）
        boolean gps = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
//        // 通过WLAN或移动网络(3G/2G)确定的位置（也称作AGPS，辅助GPS定位。主要用于在室内或遮盖物（建筑群或茂密的深林等）密集的地方定位）
//        boolean network = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
        if (gps) {
            return true;
        }

        return false;
    }

    /**
     * 强制帮用户打开GPS
     * @param context
     */
    public static final void openGPS(Context context) {

        if (isOPen(BCDApplication.getApp()))
        {
            return;
        }
        Intent GPSIntent = new Intent();
        GPSIntent.setClassName("com.android.settings",
                "com.android.settings.widget.SettingsAppWidgetProvider");
        GPSIntent.addCategory("android.intent.category.ALTERNATIVE");
        GPSIntent.setData(Uri.parse("custom:3"));
        try {
            PendingIntent.getBroadcast(context, 0, GPSIntent, 0).send();
        } catch (PendingIntent.CanceledException e) {
            e.printStackTrace();
        }
    }
}
